import { create } from 'zustand';

// 用户类型定义
export interface User {
  id: string;
  phone?: string;
  wechat?: string;
  nickname: string;
  avatar?: string;
  children: Child[];
  currentChildId?: string;
  favorites: string[];
  cart: CartItem[];
  orders: Order[];
}

// 孩子档案类型
export interface Child {
  id: string;
  name: string;
  age: number;
  gender: 'male' | 'female';
  interests: string[];
  avatar?: string;
  birthDate?: string;
  readingLevel?: string;
}

// 绘本类型
export interface PictureBook {
  id: string;
  title: string;
  author: string;
  illustrator?: string;
  publisher?: string;
  coverImage: string;
  previewImages?: string[];
  description: string;
  ageRange: string;
  category: string;
  tags: string[];
  rating: number;
  readCount: number;
  price: number;
  originalPrice?: number;
  pages: number;
  stock?: number;
  reviews?: {
    userName: string;
    rating: number;
    comment: string;
    date: string;
  }[];
}

// 活动类型
export interface Activity {
  id: string;
  title: string;
  description: string;
  image: string;
  date: string;
  time: string;
  location: string;
  category: string;
  ageRange: string;
  price: number;
  originalPrice?: number;
  spots: number;
  rating: number;
  organizer: string;
}

// 购物车项目类型
export interface CartItem {
  id: string;
  type: 'book' | 'activity';
  itemId: string;
  title: string;
  price: number;
  quantity: number;
  image: string;
  selectedOptions?: {
    childId?: string;
    date?: string;
    time?: string;
  };
}

// 订单类型
export interface Order {
  id: string;
  userId: string;
  items: CartItem[];
  totalAmount: number;
  status: 'pending' | 'paid' | 'shipped' | 'completed' | 'cancelled';
  paymentMethod?: string;
  createdAt: string;
  paidAt?: string;
  shippingAddress?: {
    name: string;
    phone: string;
    address: string;
    city: string;
    province: string;
  };
}

// 阅读记录类型
export interface ReadingRecord {
  id: string;
  userId: string;
  childId?: string;
  bookId: string;
  readAt: string;
  duration?: number;
  rating?: number;
  notes?: string;
}

// 应用状态接口
interface AppState {
  currentUser: User | null;
  books: PictureBook[];
  activities: Activity[];
  readingRecords: ReadingRecord[];
  isLoading: boolean;
  toast: {
    show: boolean;
    message: string;
    type: 'success' | 'error' | 'info';
  } | null;
}

// 应用动作接口
interface AppActions {
  // 用户操作
  login: (user: User) => void;
  logout: () => void;
  setCurrentChild: (childId: string) => void;
  toggleFavorite: (itemId: string) => void;
  
  // 数据操作
  setBooks: (books: PictureBook[]) => void;
  setActivities: (activities: Activity[]) => void;
  addReadingRecord: (record: ReadingRecord) => void;
  
  // 购物车操作
  addToCart: (item: CartItem) => void;
  removeFromCart: (itemId: string) => void;
  updateCartItemQuantity: (itemId: string, quantity: number) => void;
  clearCart: () => void;
  
  // 订单操作
  addOrder: (order: Order) => void;
  updateOrderStatus: (orderId: string, status: Order['status']) => void;
  
  // UI操作
  setLoading: (loading: boolean) => void;
  showToast: (message: string, type?: 'success' | 'error' | 'info') => void;
  hideToast: () => void;
}

// 创建Zustand store
export const useAppStore = create<AppState & AppActions>((set, get) => ({
  // 初始状态
  currentUser: null,
  books: [],
  activities: [],
  readingRecords: [],
  isLoading: false,
  toast: null,

  // 用户操作
  login: (user) => set({ 
    currentUser: { 
      ...user, 
      cart: user.cart || [], 
      orders: user.orders || [] 
    } 
  }),
  
  logout: () => set({ currentUser: null }),
  
  setCurrentChild: (childId) => {
    const { currentUser } = get();
    if (currentUser) {
      set({ currentUser: { ...currentUser, currentChildId: childId } });
    }
  },
  
  toggleFavorite: (itemId) => {
    const { currentUser } = get();
    if (currentUser) {
      const favorites = currentUser.favorites.includes(itemId)
        ? currentUser.favorites.filter(id => id !== itemId)
        : [...currentUser.favorites, itemId];
      
      set({
        currentUser: {
          ...currentUser,
          favorites
        }
      });
    }
  },

  // 数据操作
  setBooks: (books) => set({ books }),
  
  setActivities: (activities) => set({ activities }),
  
  addReadingRecord: (record) => {
    const { readingRecords } = get();
    set({ readingRecords: [record, ...readingRecords] });
  },

  // 购物车操作
  addToCart: (item) => {
    const { currentUser } = get();
    if (currentUser) {
      const existingItem = currentUser.cart.find(cartItem => 
        cartItem.itemId === item.itemId && cartItem.type === item.type
      );
      
      let updatedCart;
      if (existingItem) {
        updatedCart = currentUser.cart.map(cartItem =>
          cartItem.itemId === item.itemId && cartItem.type === item.type
            ? { ...cartItem, quantity: cartItem.quantity + item.quantity }
            : cartItem
        );
      } else {
        updatedCart = [...currentUser.cart, item];
      }
      
      set({
        currentUser: {
          ...currentUser,
          cart: updatedCart
        }
      });
    }
  },
  
  removeFromCart: (itemId) => {
    const { currentUser } = get();
    if (currentUser) {
      set({
        currentUser: {
          ...currentUser,
          cart: currentUser.cart.filter(item => item.id !== itemId)
        }
      });
    }
  },
  
  updateCartItemQuantity: (itemId, quantity) => {
    const { currentUser } = get();
    if (currentUser && quantity > 0) {
      set({
        currentUser: {
          ...currentUser,
          cart: currentUser.cart.map(item =>
            item.id === itemId ? { ...item, quantity } : item
          )
        }
      });
    }
  },
  
  clearCart: () => {
    const { currentUser } = get();
    if (currentUser) {
      set({
        currentUser: {
          ...currentUser,
          cart: []
        }
      });
    }
  },
  
  // 订单操作
  addOrder: (order) => {
    const { currentUser } = get();
    if (currentUser) {
      set({
        currentUser: {
          ...currentUser,
          orders: [order, ...currentUser.orders]
        }
      });
    }
  },
  
  updateOrderStatus: (orderId, status) => {
    const { currentUser } = get();
    if (currentUser) {
      set({
        currentUser: {
          ...currentUser,
          orders: currentUser.orders.map(order =>
            order.id === orderId ? { ...order, status } : order
          )
        }
      });
    }
  },

  // UI操作
  setLoading: (loading) => set({ isLoading: loading }),
  
  showToast: (message, type = 'info') => {
    set({ toast: { show: true, message, type } });
  },
  
  hideToast: () => set({ toast: null }),
}));

// 选择器函数 - 用于获取派生状态
export const useCurrentChild = () => {
  const currentUser = useAppStore(state => state.currentUser);
  const currentChildId = currentUser?.currentChildId;
  return currentChildId ? currentUser?.children.find(child => child.id === currentChildId) : currentUser?.children[0];
};

// 购物车相关选择器函数
export const useCartItems = () => {
  return useAppStore(state => state.currentUser?.cart || []);
};

export const useCartTotal = () => {
  const cartItems = useCartItems();
  return cartItems.reduce((total, item) => total + (item.price * item.quantity), 0);
};

export const useCartItemCount = () => {
  const cartItems = useCartItems();
  return cartItems.reduce((count, item) => count + item.quantity, 0);
};